//含拦截器和token
import axios from 'axios';
import router from '../router'
axios.defaults.timeout = 50000;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.baseURL = '/api';

//http request 拦截器
axios.interceptors.request.use(
  config => {
    config.headers = {
      'Cache-Control': 'no-cache',
      'Content-Type': 'application/json;charset=UTF-8',
    }
    if (config.url.indexOf('open') < 0) {
      const token = localStorage.getItem('token') == null ? '' : localStorage.getItem('token');
      token && (config.headers.Authorization = 'bearer ' + token);
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    return Promise.reject(error)
  }
);


export default {
  /**
   * 封装get方法
   * @param url
   * @param data
   * @returns {Promise}
   */
  get: function(url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.get(url, {
          params: params
        })
        .then(response => {
          resolve(response.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  /**
   * 封装post请求
   * @param url
   * @param data
   * @returns {Promise}
   */
  post: function(url, data, config = {}) {
    return new Promise((resolve, reject) => {
      axios.post(url, data, config)
        .then(response => {
          resolve(response.data)
        }, err => {
          reject(err)
        })
    })
  },
  /**
   * 封装put请求
   * @param url
   * @param data
   * @returns {Promise}
   */
  put: function(url, data) {
    return new Promise((resolve, reject) => {
      axios.put(url, data)
        .then(response => {
          resolve(response.data)
        }, err => {
          reject(err)
        })
    })
  },
  /**
   * 封装delete请求
   * @param url
   * @param data
   * @returns {Promise}
   */
  delete: function(url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.delete(url, {
          params: params
        })
        .then(response => {
          resolve(response.data)
        }, err => {
          reject(err)
        })
    })
  },
  /**
   * 封装patch请求
   * @param url
   * @param params
   * @returns {Promise}
   */
  patch: function(url) {
    return new Promise((resolve, reject) => {
      axios.patch(url)
        .then(response => {
          resolve(response.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
}
